//
//  NIToast.m
//  gweAD
//
//  Created by navinfo air on 2016/11/15.
//  Copyright © 2016年 mengy. All rights reserved.
//

#import "NIToast.h"
static NSMutableArray *toastArray;
static BOOL toastRemoving;
@implementation NIToast{
    
    __weak IBOutlet UIView *contentView;
    
    __weak IBOutlet UILabel *messageLabel;
    
    NSTimer *closeTimer;
}

-(void)awakeFromNib
{
    [super awakeFromNib];
    [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self.class) owner:self options:nil];
    contentView.backgroundColor = [UIColor blackColor];
    contentView.layer.masksToBounds = YES;
    contentView.layer.cornerRadius = 5.0f;
    [self addSubview:contentView];
    
    contentView.translatesAutoresizingMaskIntoConstraints = NO;
    [self addConstraint:[NSLayoutConstraint constraintWithItem:contentView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.0]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:contentView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.0]];
    
    [self addConstraint:[NSLayoutConstraint constraintWithItem:contentView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0.0]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:contentView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:0.0]];
}

-(void)setText:(NSString *)text{
    messageLabel.text = text;
}

- (CGSize)sizeToFit{
    UILabel *tempLabel = [[UILabel alloc] init];
    [tempLabel setFrame:CGRectMake(0, 0, MAXFLOAT, 50)];
    tempLabel.numberOfLines = 0;
    tempLabel.text = messageLabel.text;
    tempLabel.font = messageLabel.font;
    [tempLabel sizeToFit];
    
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    
    if (tempLabel.frame.size.width <= window.frame.size.width*2/3) {
        
    }else{
        [tempLabel setFrame:CGRectMake(0, 0, window.frame.size.width*2/3, MAXFLOAT)];
        [tempLabel sizeToFit];
    }
    return CGSizeMake(tempLabel.frame.size.width + 20, tempLabel.frame.size.height + 20);
}

- (void)show{
    closeTimer = [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(close) userInfo:nil repeats:NO];
}

- (void)closeAndStopTimer:(void (^)()) finishBlock{
    [closeTimer invalidate];
    [self close:finishBlock];
}

- (void)close{
    [UIView animateWithDuration:1.0f animations:^{
        self.alpha = 0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}
- (void)close:(void (^)()) finishBlock{
    [UIView animateWithDuration:1.0f animations:^{
        self.alpha = 0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
        finishBlock();
    }];
}

+ (void)addtoast:(nonnull NSString *)text{
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    NIToast *toast = [[NIToast alloc] init];
    [toast awakeFromNib];
    toast.text = text;
    CGSize size = [toast sizeToFit];
    toast.frame = CGRectMake((window.frame.size.width - size.width)/2, window.frame.size.height - size.height - 40, size.width, size.height);
    [toast setBackgroundColor:[UIColor clearColor]];
    if (!toastArray) {
        toastArray = [[NSMutableArray alloc] initWithCapacity:0];
    }
    [toastArray addObject:toast];
}


+ (BOOL)hastoast{
    BOOL hastoast = NO;
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    for (UIView *view in window.subviews) {
        //多个toast显示情况，1.快速显示第一个toast
        if ([view isKindOfClass:[NIToast class]]) {
            hastoast = YES;
            [window bringSubviewToFront:view];
            break;
        }
    }
    return hastoast;
}
+ (BOOL)removeToast:(void (^)()) finishBlock{
    BOOL hasToast = NO;
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    for (UIView *view in window.subviews) {
        //多个toast显示情况，1.快速显示第一个toast
        if ([view isKindOfClass:[NIToast class]]) {
            hasToast = YES;
            toastRemoving = YES;
            [window bringSubviewToFront:view];
            //2.快速关闭toast
            [(NIToast *)view closeAndStopTimer:^{
                finishBlock();
            }];
            break;
        }
    }
    return hasToast;
}

+ (void)show{
    BOOL hasToast = NO;
    if (toastArray.count > 0) {
        //删除前面的toast（window中只保持至多存在1个toast）
        if (!toastRemoving) {
            hasToast = [NIToast removeToast:^{
                toastRemoving = NO;
                //显示下一个toast
                [NIToast show];
            }];
            //如果当前没有在显示的toast则显示数组中的第一个toast
            if (!hasToast){
                NIToast *toast = [toastArray objectAtIndex:0];
                UIWindow *window = [[UIApplication sharedApplication] keyWindow];
                [window addSubview:toast];
                [toast show];
                [toastArray removeObject:toast];
                if (toastArray.count > 0) {
                    [NIToast show];
                }
            }
        }
    }
}

+ (void)showInfo:(nonnull NSString *)text{
    //加入管理,并不显示
    [NIToast addtoast:text];
    [NIToast show];
}

@end
